//
//  MTNewClubDetailViewController.swift
//  MT
//
//  Created by ooops on 2020/5/11.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import YPNavigationBarTransition
import MTCategory
import Eureka

class MTNewClubDetailViewController: BaseFormViewController {
    
    public var group: JMSGGroup!
    private var model: MTClubRichListResultModel?
    var comformChat: Bool = false
    
    private lazy var clubProvider: MTProvider<MTClubApi> = {
        let provider = MTProvider<MTClubApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    convenience init(group: JMSGGroup, model: MTClubRichListResultModel) {
        self.init()
        self.group = group
        self.model = model
        //self.completeClosure = updateClubClosure
        //users = group.memberArray()
        //self.tableView.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        title = "俱乐部详情"
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white, NSAttributedString.Key.font:PingFangSCSemiboldFont(16)]
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        makeConstraint()
        if let navGesture = self.navigationController?.interactivePopGestureRecognizer {
            tableView.panGestureRecognizer.require(toFail: navGesture)
        }

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        tableView.tableHeaderView = headerView
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor(hex: 0xF4F4F4)
        view.backgroundColor = UIColor(hex: 0xF4F4F4)
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50 + ScreenBottomExtraOffset, right: 0)
        
        view.addSubview(bottomBgView)
        bottomBgView.addSubview(commitButton)
        
        bottomBgView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(50 + ScreenBottomExtraOffset)
        }
        
        commitButton.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(10)
            make.centerX.equalToSuperview()
            make.width.equalTo(266)
            make.height.equalTo(40)
        }
        /// 设置头部信息
        self.headerView.model = self.model
        self.setValue(value: "", forTag: clubDescriptionKey)
        checkIsMemberOfClub()
        queryClubInfo()
        tableView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
    }
    
    private func queryClubInfo() {
        //guard let id = group.gid else { return }
        MTClubTool.queryClubInfo(provider: clubProvider, requestParam: ["pushId": group.gid], complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200 {
                weakSelf.headerView.model = m.result
            }
            
        }) { (error) in
            
        }
    }
    
    private func checkIsMemberOfClub() {
        /// 是俱乐部拥有者 / 俱乐部成员 不显示加入俱乐部按钮
        let localUser = JMSGUser.myInfo()
        group.memberArray { [weak self] (result, error) in
            guard let weakSelf = self else { return }
            if error == nil, let users = result as? [JMSGUser] {
                let haveUser = users.contains(where: { (u) -> Bool in
                    return u.username == localUser.username
                })
                
                if haveUser || weakSelf.group.owner == JMSGUser.myInfo().username {
//                    weakSelf.bottomBgView.isHidden = true
                    weakSelf.commitButton.setTitle("进入聊天", for: .normal)
                    weakSelf.tableView.contentInset = UIEdgeInsets.zero
                }
            }
        }
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    lazy var bottomBgView: UIView = {
        let v = UIView()
        v.backgroundColor = .black
        return v
    }()
    
    lazy var commitButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("申请加入", for: .normal)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        //btn.isUserInteractionEnabled = false
        btn.layer.cornerRadius = 20
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(commitClub), for: .touchUpInside)
        return btn
    }()
    
    lazy var headerView: MTNewClubDetailHeaderView = {
        let v = MTNewClubDetailHeaderView()
        v.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 277)
        return v
    }()
    
    /// 赋值
    /// - Parameters:
    ///   - value:
    ///   - tag:
    private func setValue(value: String, forTag tag: String) {
        switch tag {
        case clubDescriptionKey:
            if let row: MTNewClubRemarkCellRow = self.form.rowBy(tag: tag) as? MTNewClubRemarkCellRow {
                if value.count > 0 {
                    row.value = value
                    row.cell.contentString = value
                } else {
                    if let areaArray = group.desc?.components(separatedBy: groupInfoSeprate), let desc = areaArray.first {
                        row.cell.contentString = desc
                        row.value = desc
                    }
                }
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                    cell.height = { UITableView.automaticDimension }
                }
            }
        case clubMemberKey:
            if let row: MTNewClubDetailMemberRow = self.form.rowBy(tag: tag) as? MTNewClubDetailMemberRow {
                if self.group != nil {
                    row.cell.group = self.group
                    row.reload()
                    row.cellUpdate { (cell, row) in
                        cell.height = { UITableView.automaticDimension }
                    }
                }
            }
        default:
            break
        }
    }
    
    private func setupUI() {
        let sectionTwo = Section()
        form +++ sectionTwo
            <<< MTNewClubRemarkCellRow(){ row in
                row.cell.tipString = "俱乐部简介"
                row.cell.contentString = "这是一个很好玩的活动，为了迎接新年到来，我们将在好日子酒吧举办一场跨年狂欢。"
                //row.cell.placeholder = "快来给大家介绍下你的俱乐部特色吧"
                row.cell.contentType = .editTextMutiply
                row.cell.isEditMode = false
                
                row.tag = clubDescriptionKey
                row.cell.maxTextLength = 50
                //row.cell.height = { return 120 }
                row.cell.clubRemarkViewHeight = self.caculatorTextHeight(contentString: "这是一个很好玩的活动，为了迎接新年到来，我们将在好日子酒吧举办一场跨年狂欢。")
                row.cell.height = { return self.caculatorTextHeight(contentString: "这是一个很好玩的活动，为了迎接新年到来，我们将在好日子酒吧举办一场跨年狂欢。") + 69}
                row.cell.clubRemarkViewScrollEnable = false
                row.cell.backgroundColor = UIColor(hex: 0xffffff)
                //row.add(rule: MTClubExDetailNotNullRule())
                row.updateCell()
            }.onChange({ (row) in
                //self.validatorDataDictionary()
            })
        
            <<< MTNewClubDetailMemberRow(){ row in
                row.tag = clubMemberKey
                row.cell.delegate = self
                //row.hidden = Condition(booleanLiteral: isEditMode)
                row.cell.group = self.group
            }
        
        GroupTableSeparatorFix.removeFirstAndLastSeparatorLine()
    }
    
    private func caculatorTextHeight(contentString: String) -> CGFloat {
        //PingFangSCMediumFont(14)
        return contentString.height(font: PingFangSCMediumFont(14), maxWidth: ScreenWidth - 40)
    }
    
    private func makeConstraint() {
        
    }
}


extension MTNewClubDetailViewController {
    private func chat() {
        /// 如果是从聊天界面过来的, 直接pop掉就好
        if comformChat {
            self.navigationController?.popViewController(animated: true)
            return
        }
        JMSGGroup.groupInfo(withGroupId: "\(self.group.gid)", completionHandler: { (result, error) in
            if error == nil, let group = result as? JMSGGroup {
                /// 不是这个组的成员
                group.memberInfoList({ (result, error) in
                    if error == nil {
                        if let userInfos: [JMSGGroupMemberInfo] = result as? [JMSGGroupMemberInfo] {
                            let r : [JMSGUser?] = userInfos.map { (info) -> JMSGUser? in
                                return info.user
                            }
                            /// 判断是否是俱乐部成员
                            if r.contains(JMSGUser.myInfo()) == false {
                                MBProgressHUD_JChat.show(text: "请先加入俱乐部", view: self.view)
                                return
                            }
                            /// 创建群聊会话
                            JMSGConversation.createGroupConversation(withGroupId: "\(self.group.gid)") { [weak self] (conversation, error) in
                                guard let weakSelf = self else { return }
                                if error == nil, conversation != nil {
                                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[2] as? BaseNavController {
                                        nav.selectClub()
                                        
                                        NotificationCenter.default.post(name: GlobalNotificationName.didPushChat.name, object: nil, userInfo: nil)
                                        
                                        DispatchQueue.main.after(0, execute: {
                                            weakSelf.navigationController?.popToRootViewController(animated: false)
                                        })
                                        
                                        DispatchQueue.main.after(0.25) {
                                            let conv: JMSGConversation = conversation as! JMSGConversation
                                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                                        }
                                        
//                                        DispatchQueue.main.after(1, execute: {
//                                            weakSelf.navigationController?.popToRootViewController(animated: false)
//                                        })
                                    }
                                }
                            }
                        }
                    }
                })
            }
        })
    }
    
    @objc private func commitClub() {
        
        let localUser = JMSGUser.myInfo()
        group.memberArray { [weak self] (result, error) in
            guard let weakSelf = self else { return }
            if error == nil, let users = result as? [JMSGUser] {
                let haveUser = users.contains(where: { (u) -> Bool in
                    return u.username == localUser.username
                })
                
                if haveUser || weakSelf.group.owner == JMSGUser.myInfo().username {
                    weakSelf.chat()
                    return
                }
            } else {
                return
            }
        }
                
        guard let clubName = model?.pushId else { return }
        
        /// 判断群组类型是否为公开俱乐部
        JMSGGroup.groupInfo(withGroupId: "\(clubName)", completionHandler: { (result, error) in
            if error == nil {
                /**
                 * 可申请的俱乐部满足的条件
                 *
                 * 如果俱乐部存在
                 * 俱乐部是公开类型
                 * 俱乐部不是自己的
                 */
                guard let group: JMSGGroup = result as? JMSGGroup, group.groupType != .private, group.owner != JMSGUser.myInfo().username else { return }
                
                /// 公开俱乐部
                JMSGGroup.applyJoin(withGid: "\(clubName)", reason: nil) { [weak self] (result, error) in
                    guard let weakSelf = self else { return }
                    if error == nil {
                        let currentUser = JMSGUser.myInfo()
                        let info = JCVerificationInfo.create(username: "\(clubName)", nickname: weakSelf.model?.name ?? "", appkey: currentUser.appKey!, resaon: "申请加入俱乐部\(group.name ?? "")", state: JCVerificationType.wait.rawValue, initiator: currentUser.username, type: MTRequestVerifyType.group, eventId: "", clubId: "\(clubName)")
                        
                        JCVerificationInfoDB.shareInstance.insertData(info)
                        NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
                        MBProgressHUD_JChat.show(text: "加入俱乐部请求已发送", view: weakSelf.view, 2)
                    } else {
                        if (error! as NSError).code == 856003 {
                            MBProgressHUD_JChat.show(text: "申请已发送, 请耐心等待审核", view: weakSelf.view)
                        }
                    }
                }
                
            }
        })
        
    }
}

extension MTNewClubDetailViewController: MTNewClubDetailMemberCellDelegate {
    /// 查看更多成员按钮
    func clickMoreButton(clickButton button: UIButton) {
        let vc = MTMemberViewController(group: self.group)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    /// 点击用户
    func didSelectCell(user: JMSGUser) {
        let c = MineViewController(username: user.username)
        navigationController?.pushViewController(c, animated: true)
    }
    
}

extension MTNewClubDetailViewController {

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleTransparent]
    }
    
    override func yp_navigationBarTintColor() -> UIColor! {
        return UIColor.white
    }
}

